const nrOfPlayers = 9;
const avatarFolder = "resources/avatars/";
const cardFolder = "resources/cards/";

const counterKey = "typokerChatCounter";
const chatKey = "typokerChat"; 

var initialized = false;
var started = false;
var noButtons = true;
var active = nrOfPlayers + 1;
var winners = [];

var playerName = "Guest";
var avatar = "anon.png";
var avatarName;

$(document).ready(function () {
	dwr.engine.setActiveReverseAjax(true);
	
	if (!localStorage[counterKey]) {
		localStorage[counterKey] = 0;
	}
	
	$('#gameTableBg').ready(function () {
		$('#gameTableBg').css('height', $('#gameTableHolder').height() + "px");
	});
	
	$('#chatArea').ready(function () {
		$('#chatArea').css('height', $('#chat').height() * 0.7 + "px");
	});
	
	$('#chatSubmit').mousedown(function() {
		message = $('#chatInput').val();
		if (message !== "") {
			addMessage(playerName, message);
		}
		$('#chatInput').val("");
	});
	
	$('#chatInput').keypress(function (event) {
		if (event.which == 13){
			message = $('#chatInput').val();
			if (message !== "") {
				addMessage(playerName, message);
			}
			$('#chatInput').val("");
	    }
	});
	
	GameProxy.newGame();
});

$(window).resize(function () {
	$('#gameTableBg').ready(function () {
		$('#gameTableBg').css('height', $('#gameTableHolder').height() + "px");
	});
	
	$('#chatArea').ready(function () {
		$('#chatArea').css('height', $('#chat').height() * 0.7 + "px");
	});
});

function addMessage(playerName, message) {
	var temp = playerName + " :: " + message;
	
	chatMessage(temp);
	
	i = localStorage[counterKey];
	localStorage[chatKey + i] = temp;
	localStorage[counterKey] = ++i;
}

function chatMessage(message) {
	$('#chatArea').val($('#chatArea').val() + (message + "\n"));
	$('#chatArea').animate({ scrollTop: $('#chatArea')[0].scrollHeight }, 1000);
}

function startNewGame() {
	if (!started) {
		started = true;
		
		i = localStorage[counterKey];
		localStorage[chatKey + i] = "*** New chat ***";
		localStorage[counterKey] = ++i;
		
		$('#offline').css('visibility', 'visible');
		$('#joiningPanelContainer').css('visibility', 'visible');
		
		clearTable();
		
		$('#nameInput').val(playerName);
		
		$('#leaveGame').mousedown(function() {
			window.location.href = "index.html";
		});
		
		$('#startGame').mousedown(function() {
			$('#joiningPanelContainer').css('visibility', 'hidden');
			$('#offline').css('visibility', 'hidden');
			$('#nameInput').val(playerName);
			
			initialized = false;
			GameProxy.startGame(playerName, avatar);
		});
		
		$('#submitInfo').mousedown(function() {
			playerName = $('#nameInput').val();
			if(playerName != "" && avatarName != ""){
				$('#pickAvatarContainer').fadeOut('normal');
				$('#infoSumbitError').text("");
			}else{
				$('#infoSumbitError').text("Fill all the fields!").css('color','white');
			}
		});

		$('#pickYourAvatar').mousedown(function() {
			$('#pickAvatarContainer').css('visibility','visible').fadeIn('normal');
		});

		$('#nameInput').mousedown(function() {
			$('#nameInput').val("");
		});
	}
}

function selectAvatar(avatarId) {
    if(avatarName != ""){
        $("#" + avatarName).css('border-color','black');
    }
    $("#" + avatarId).css('border-color','white');
    avatarName = avatarId;
    avatar = avatarName + ".jpg";
}

function restoreGame(sb, bb, game) {
	if (!initialized) {
		initialized = true;
		
		$('#offline').css('visibility', 'hidden');
		
		setupTable();
		
		setSB(sb);
		setBB(bb);
		setRaise(game.step);
		setPot(game.pot);
		
		$.each(game.players, function(id, player) {
			setPlayer(id, player);
		});
		
		setDealer(game.dealer);
		
		markHuman(game.human);
		playerName = game.players[game.human].name;
		avatar = game.players[game.human].image;
		
		if (game.position < nrOfPlayers) {
			enableActive(game.position);
		}
		
		$.each(game.commCards, function(id, card) {
			if (card != null) {
				$('#commCards').append("<img id='commCard" + id +
						"' class='dealt' src='" + cardFolder + card.image + "'/>");
			}
		});
	}
}

function setPlayer(id, player) {
	$('#gameTable').append(
			"<div id='player" + id + "' class='player'>" +
				"<div class='playerImage'><img class='avatar' " +
				"src='" + avatarFolder + player.image + "'/></div>" +
				"<div class='playerName'>" + player.name + "</div>" +
				"<div class='playerMoney'>" +
					"<img src='resources/cash.png' style='float: left' />" +
					"<span class='sum'>" + player.cash + " $</span>" +
				"</div>" +
			"</div>" +
			"<div id='hand" + id + "' class='hand'></div>" +
			"<div id='dealer" + id + "' class='dealer'></div>" +
			"<div id='bet" + id + "' class='bet'></div>");
	
	if (player.inGame) {
		$.each(player.cards, function(nr, card) {
			if (card != null) {
				$("#hand" + id).append("<img id='card" + id + nr +
						"' class='dealt' src='" + cardFolder + card + "'/>");
			}
		});
		
		updateBet(id, player.bet);
	} else {
		$("#player" + id).css('opacity', '0.5');
	}
}

function updatePlayer(id, player) {
	$("div#player" + id + " .sum").text(player.cash + " $");

	if (!player.inGame) {
		$("#player" + id).css('opacity', '0.5');
	}

	updateBet(id, player.bet);
}

function updateBet(id, sum) {
	if (sum > 0) {
		$("#bet" + id).text(sum + " $");
	} else {
		$("#bet" + id).text("");
	}
}

function setDealer(id) {
    $("#dealer" + id).html("<img id='dealerButton' src='resources/dealer.png'/>");
}

function updateDealer(prev_id, id) {
    $('#dealerButton').appendTo('#gameTable');
    $('#dealerButton').css({
    	'position' : 'absolute',
    	'top' : $("#dealer" + prev_id).css('top'),
    	'left' : $("#dealer" + prev_id).css('left')
    });
    $('#dealerButton').animate({
    	'top' : $("#dealer" + id).css('top'),
    	'left' : $("#dealer" + id).css('left')},
    	500, 'linear',
    	function () {
    		$('#dealerButton').attr('style');
    		$('#dealerButton').removeAttr('style');
    		$('#dealerButton').appendTo("#dealer" + id);
    });
}

function markHuman(id) {
	var top = parseInt($("#player" + id).css('top')) - 5 + "px";
    var left = parseInt($("#player" + id).css('left')) - 5 + "px";
    $('#gameTable').append("<img id='human' src='resources/human.png'/>");
    $('#human').css({
    	'position' : 'absolute',
    	'top' : top,
    	'left' : left,
    	'height' : '30px',
    	'width' : '30px'
    	});
}

function enableActive(id) {
	$("#player" + id).addClass('active');
	active = id;
}

function disableActive() {
	$("#player" + active).removeClass('active');
	active = nrOfPlayers + 1;
}

function updateActive(id) {
	disableActive();
	enableActive(id);
}

function enableWinners(_winners) {
	winners = _winners;
	$.each(winners, function(index, id) {
		$("#player" + id).addClass('winner');
	});
}

function disableWinners() {
	$.each(winners, function(index, id) {
		$("#player" + id).removeClass('winner');
	});
	winners = [];
}

function dealCard(id, card, nr) {
	var name = "card" + id + nr;
	var leftCoord = parseInt($("#hand" + id).css('left')) + nr * 45 + "px";
	$('#gameTable').append("<img id='"+name+"' class='notDealt' src='" + cardFolder + card + "'/>");
	$("#" + name).animate({
		'top' : $("#hand" + id).css('top'),
		'left' : leftCoord},
		300, 'linear',
		function() {
			 $("#" + name).removeClass('notDealt');
			 $("#" + name).removeAttr('style');
			 $("#" + name).addClass('dealt');
			 $("#" + name).appendTo("#hand" + id);
		});
}

function dealCommCard(card, nr) {
	var name = "commCard" + nr;
	var leftCoord = parseInt($('#commCards').css('left')) + nr * 45 + "px";
	$('#gameTable').append("<img id='"+name+"' class='notDealt' src='" + cardFolder + card + "'/>");
	$("#" + name).animate({
			'top' : $('#commCards').css('top'),
			'left' : leftCoord},
			300, 'linear',
			function() {
				 $("#" + name).removeClass('notDealt');
				 $("#" + name).removeAttr('style');
				 $("#" + name).addClass('dealt');
				 $("#" + name).appendTo('#commCards');
			});
}

function burnCard() {
	$('#gameTable').append("<img id='burn' class='notDealt' src='" + cardFolder + "B.png'/>");
	$('#burn').animate({
			'top' : $('#burnCard').css('top'),
			'left' : $('#burnCard').css('left')},
			300, 'linear',
			function() {
				 $('#burn').removeClass('notDealt');
				 $('#burn').removeAttr('style');
				 $('#burn').addClass('dealt');
				 $('#burn').appendTo('#burnCard');
			});
	$('#burn').fadeOut(500, function () {$('#burn').remove();});
}

function foldCards(id) {
	var name = "card" + id;
	$("#" + name + "0").removeClass('dealt').appendTo('#gameTable').css({
		'position':'absolute',
		'top': $("#hand" + id).css('top'),
		'left': $("#hand" + id).css('left')
	});
	$("#" + name + "1").remove();
	
    $("#" + name + "0").animate({
    	'top': $('#deck').css('top'),
    	'left': $('#deck').css('left')},
    	500, 'linear',
    	function () {$("#" + name + "0").remove();}
    );
}

function showHand(id, cards) {
	$("#hand" + id).empty();
	$("#hand" + id).append(
			"<img id='card" + id + "0' class='dealt' src='" + cardFolder + cards[0] + "'/>" +
			"<img id='card" + id + "1' class='dealt' src='" + cardFolder + cards[1] + "'/>");
}

function removeCommCards() {
	$('#commCards').fadeOut(400, function () {
		$('#commCards').empty();
		$('#commCards').attr('style');
		$('#commCards').removeAttr('style');
	});
}

function setSB(value){
    $('#sb').text(value + " $");
}
function setBB(value){
    $('#bb').text(value + " $");
}
function setRaise(value){
    $('#raise').text(value + " $");
}
function setPot(value){
    $('#pot').text(value + " $");
}

function endRound() {
	setPot(0);
	
	for (i = 0; i < nrOfPlayers; i++) {
		$("#hand" + i).empty();
	}
	
	removeCommCards();
	disableWinners();
}

function setupTable() {
	setupGameInfo();
	$('#gameTable').append("<div id='burnCard'></div>");
	$('#gameTable').append("<div id='commCards'></div>");
	$('#gameTable').append("<div id='deck'></div>");
}

function setupGameInfo () {
	$('#gameTable').append(
			"<div id='gameInfoHolder'>" +
				"<div id='gameInfo'>" +
					"<span class='label'>Small Blind</span>" +
					"<span id='sb' class='value'></span><br/>" +
					"<span class='label'>Big Blind</span>" +
					"<span id='bb' class='value'></span><br/>" +
					"<span class='label'>Raise</span>" +
					"<span id='raise' class='value'></span><br/>" +
					"<span class='label'>Pot</span>" +
					"<span id='pot' class='value'></span>" +
				"</div>" +
			"</div>");
}

function clearTable() {
	$('#gameTable').empty();
	disableButtons();
	$('#chatArea').val("");
	winners = [];
}

function leaveTable() {
	GameProxy.leaveGame();
	clearTable();
	started = false;
	GameProxy.newGame();
}

function enableButtons(buttons) {
	if (noButtons) {
		noButtons = false;
		$.each(buttons, function(id, button) {
			switch (button) {
				case 1:
					enableFold();
					break;
				case 2:
					enableCheck();
					break;
				case 3:
					enableCall();
					break;
				case 4:
					enableRaise();
					break;
				case 5:
					enableAllin();
					break;
				default:
					break;
			}
		});
	}
}

function enableFold() {
	$('#buttonsContainer').append("<input class='button large red' " +
			"type='button' value='Fold' onclick='GameProxy.humanMove(1)' />");
}

function enableCheck() {
	$('#buttonsContainer').append("<input class='button large orange' " +
			"type='button' value='Check' onclick='GameProxy.humanMove(2)' />");
}

function enableCall() {
	$('#buttonsContainer').append("<input class='button large orange' " +
			"type='button' value='Call' onclick='GameProxy.humanMove(3)' />");
}

function enableRaise() {
	$('#buttonsContainer').append("<input class='button large green' " +
			"type='button' value='Raise' onclick='GameProxy.humanMove(4)' />");
}

function enableAllin() {
	$('#buttonsContainer').append("<input class='button large green' " +
			"type='button' value='All-in' onclick='GameProxy.humanMove(5)' />");
}

function disableButtons() {
	$('#buttonsContainer').empty();
	noButtons = true;
}